<?php
/************************************************************
 * Copyright (C), 1993, Dacelve. Tech., Ltd.
 * FileName : mysql.php
 * Author   : Lizhijian
 * Version  : 1.0
 * Date     : 2018/1/16 17:26
 * Description   :
 * Function List :
 * History  :
 * <author>    <time>    <version >    <desc>
 * Lizhijian   2018/1/16   1.0          init
 ***********************************************************/

$serv = new swoole_server("0.0.0.0", 9508);
$serv->set(array(
    'worker_num' => 2,
    'task_worker_num' => 8, //database connection pool
    'db_uri' => 'mysql:host=0.0.0.0;dbname=fast',
    'db_user' => 'admin',
    'db_passwd' => 'admin123',
    //    'task_worker_max'=>100
));

$serv->on('receive', function ($serv, $fd, $from_id, $data){
    //taskwait就是投递一条任务，这里直接传递SQL语句了 //然后阻塞等待SQL完成
    $result = $serv->taskwait($data);
    if ($result !== false) {
        list($status, $db_res) = explode(':', $result, 2);

        if ($status == 'OK') {
            //数据库操作成功了，执行业务逻辑代码，这里就自动释放掉MySQL连接的占用
            $serv->send($fd, json_encode(unserialize($db_res)) . "\n");
        } else {
            $serv->send($fd, $db_res);
        }
        return;
    } else {
        $serv->send($fd, "Error. Task timeout\n");
    }
});

$serv->on('task', function ($serv, $task_id, $from_id, $sql){
    static $link = null;
    if ($link == null) {
        $link = mysqli_connect("120.79.209.186", "admin", "admin123", "fast", 3306);
        if (!$link) {
            $link = null;
            $serv->finish("ER:" . mysqli_error($link));
            return;
        }
    }
    $result = $link->query($sql);
    if (!$result) {
        $serv->finish("ER:" . mysqli_error($link));
        return;
    }
    $data = $result->fetch_all(MYSQLI_ASSOC);
    $serv->finish("OK:" . serialize($data));
});

$serv->on('finish', function ($serv, $task_id, $data){
    echo "任务完成";//taskwait 没有触发这个函数。。
    echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL;
});


$serv->start();
